import datetime

import Logger
from GetStations import *
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import *
from QueryRequest import *
from PyQt6.QtGui import *

import sys
import time

def GetTime():
    now = int(time.time())
    timeStruct = time.localtime(now)
    strTime = time.strftime("%Y-%m-%d", timeStruct)
    return strTime

def IsValidDate(str):
    try:
        time.strptime(str,"%Y-%m-%d")
        return True
    except:
        return False

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(750, 500)
        MainWindow.setMaximumSize(750,500)
        MainWindow.setMinimumSize(750,500)
        self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayoutWidget = QtWidgets.QWidget(parent=self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 721, 80))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(parent=self.verticalLayoutWidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(parent=self.verticalLayoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.label_2 = QtWidgets.QLabel(parent=self.verticalLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(parent=self.verticalLayoutWidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout.addWidget(self.lineEdit_2)
        self.label_3 = QtWidgets.QLabel(parent=self.verticalLayoutWidget)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout.addWidget(self.label_3)
        self.lineEdit_3 = QtWidgets.QLineEdit(parent=self.verticalLayoutWidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout.addWidget(self.lineEdit_3)
        self.pushButton = QtWidgets.QPushButton(parent=self.verticalLayoutWidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_4 = QtWidgets.QLabel(parent=self.verticalLayoutWidget)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_2.addWidget(self.label_4)
        self.checkBox = QtWidgets.QCheckBox(parent=self.verticalLayoutWidget)
        self.checkBox.setObjectName("checkBox")
        self.horizontalLayout_2.addWidget(self.checkBox)
        self.checkBox_2 = QtWidgets.QCheckBox(parent=self.verticalLayoutWidget)
        self.checkBox_2.setObjectName("checkBox_2")
        self.horizontalLayout_2.addWidget(self.checkBox_2)
        self.checkBox_3 = QtWidgets.QCheckBox(parent=self.verticalLayoutWidget)
        self.checkBox_3.setObjectName("checkBox_3")
        self.horizontalLayout_2.addWidget(self.checkBox_3)
        self.checkBox_4 = QtWidgets.QCheckBox(parent=self.verticalLayoutWidget)
        self.checkBox_4.setObjectName("checkBox_4")
        self.horizontalLayout_2.addWidget(self.checkBox_4)
        self.checkBox_5 = QtWidgets.QCheckBox(parent=self.verticalLayoutWidget)
        self.checkBox_5.setObjectName("checkBox_5")
        self.horizontalLayout_2.addWidget(self.checkBox_5)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.tableView = QtWidgets.QTableView(parent=self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 150, 731, 321))
        self.tableView.setObjectName("tableView")
        self.model = QStandardItemModel()
        self.tableView.horizontalHeader().setVisible(True)
        self.tableView.verticalHeader().setVisible(True)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(parent=MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 750, 21))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(parent=self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuHelp = QtWidgets.QMenu(parent=self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        MainWindow.setMenuBar(self.menubar)
        self.actionExit = QtGui.QAction(parent=MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionUsage = QtGui.QAction(parent=MainWindow)
        self.actionUsage.setObjectName("actionUsage")
        self.actionAbout = QtGui.QAction(parent=MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.actionDownloadFile = QtGui.QAction(parent=MainWindow)
        self.actionDownloadFile.setObjectName("actionAbout")
        self.menuFile.addAction(self.actionDownloadFile)
        self.menuFile.addAction(self.actionExit)
        self.menuHelp.addAction(self.actionUsage)
        self.menuHelp.addAction(self.actionAbout)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Crack 12306"))
        self.label.setText(_translate("MainWindow", "From:"))
        self.label_2.setText(_translate("MainWindow", "To:"))
        self.label_3.setText(_translate("MainWindow", "Date:"))
        self.pushButton.setText(_translate("MainWindow", "Query Ticket"))
        self.label_4.setText(_translate("MainWindow", "Ticket Type:"))
        self.checkBox.setText(_translate("MainWindow", "GC"))
        self.checkBox_2.setText(_translate("MainWindow", "D"))
        self.checkBox_3.setText(_translate("MainWindow", "Z"))
        self.checkBox_4.setText(_translate("MainWindow", "T"))
        self.checkBox_5.setText(_translate("MainWindow", "K"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.menuHelp.setTitle(_translate("MainWindow", "Help"))
        self.actionDownloadFile.setText("Download Station File")
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionUsage.setText(_translate("MainWindow", "Usage"))
        self.actionAbout.setText(_translate("MainWindow", "About"))

        self.lineEdit_3.setText(GetTime())
        self.pushButton.clicked.connect(self.On_Button1_Click)
        self.checkBox.stateChanged.connect(self.Change_G)
        self.checkBox_2.stateChanged.connect(self.Change_D)
        self.checkBox_3.stateChanged.connect(self.Change_Z)
        self.checkBox_4.stateChanged.connect(self.Change_T)
        self.checkBox_5.stateChanged.connect(self.Change_K)

    def Change_G(self,state):
        if state == QtCore.Qt.CheckState.Checked:
            GetGVehicle()
            self.DisplayTable(len(type_data), 16, type_data)
        else:
            RemoveGVehicle()
            self.DisplayTable(len(type_data), 16, type_data)

    def Change_D(self,state):
        if state == QtCore.Qt.CheckState.Checked:
            GetDVehicle()
            self.DisplayTable(len(type_data), 16, type_data)
        else:
            RemoveDVehicle()
            self.DisplayTable(len(type_data), 16, type_data)


    def Change_Z(self, state):
        if state == QtCore.Qt.CheckState.Checked:
            GetZVehicle()
            self.DisplayTable(len(type_data), 16, type_data)
        else:
            RemoveZVehicle()
            self.DisplayTable(len(type_data), 16, type_data)

    def Change_T(self,state):
        if state == QtCore.Qt.CheckState.Checked:
            GetTVehicle()
            self.DisplayTable(len(type_data), 16, type_data)
        else:
            RemoveTVehicle()
            self.DisplayTable(len(type_data), 16, type_data)

    def Change_K(self,state):
        if state == QtCore.Qt.CheckState.Checked:
            GetKVehicle()
            self.DisplayTable(len(type_data), 16, type_data)
        else:
            RemoveKVehicle()
            self.DisplayTable(len(type_data), 16, type_data)

    def MessageBox(self, title, message):
        QMessageBox.warning(None, title, message)
        Logger.Print_Error(message[6:])


    def DisplayTable(self, train, info, data):
        self.model.clear()
        self.model.setHorizontalHeaderLabels(["车次", "出发站", "到达站", "出发时间", "到达时间",
                                                  "用时", "特等座", "一等座", "二等座",
                                                  "高级软卧", "软卧", "动卧", "硬卧", "软座", "硬座", "无座"])
        for row in range(train):
            for column in range(info):
                item = QStandardItem(data[row][column])
                self.model.setItem(row, column, item)
        self.tableView.setModel(self.model)

    def CheckBox_Default(self):
        self.checkBox.setChecked(False)
        self.checkBox_2.setChecked(False)
        self.checkBox_3.setChecked(False)
        self.checkBox_4.setChecked(False)
        self.checkBox_5.setChecked(False)

    def On_Button1_Click(self):
        get_from = self.lineEdit.text()
        get_to = self.lineEdit_2.text()
        get_date = self.lineEdit_3.text()
        if IsStations():
            stations = eval(Read())
            if get_from != "" and get_to != "" and get_date != "":
                if get_from in stations and get_to in stations and IsValidDate(get_date):
                    inputYearDay = time.strptime(get_date,"%Y-%m-%d").tm_yday
                    yearToday = time.localtime(time.time()).tm_yday
                    timeDifference = inputYearDay - yearToday
                    if timeDifference >=0 and timeDifference<=28:
                        from_station = stations[get_from]
                        to_station = stations[get_to]
                        data = Query(get_date,from_station,to_station)
                        Logger.Print_Info("Query: FromStation="+from_station+" ToStation="+to_station+" Date="+get_date)
                        self.CheckBox_Default()
                        if len(data)!=0:
                            self.DisplayTable(len(data),16, data)
                        else:
                            self.MessageBox("Crack 12306", "Error: No response data")
                    else:
                        self.MessageBox("Crack 12306", "Error: Date out of range")
                else:
                    self.MessageBox("Crack 12306", "Error: Invaild station name or date")
            else:
                self.MessageBox("Crack 12306", "Error: Please input station name and required infomation")
        else:
            self.MessageBox("Crack 12306", "Error: Can't find stations file(stations.text) You must be restart Crack 12306")


def StartUp():
    application = QtWidgets.QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create("Fusion"))
    mainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(mainWindow)
    mainWindow.show()
    Logger.Print_Success("Crack 12306 is start on "+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
    Logger.Print_Success("Welcome to Crack 12306")
    sys.exit(application.exec())

if __name__ == "__main__":
    if IsStations():
        StartUp()
    else:
        GetStation()
        StartUp()